package tool

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"time"

	"github.com/astaxie/beego/orm"
)

type Time20 struct {
	time.Time
	IgnoreSecond bool
}
type Time10 struct {
	time.Time
}

// MarshalJSON 序列化为JSON
func (t Time20) MarshalJSON() ([]byte, error) {
	if t.IsZero() {
		return []byte("\"\""), nil
	}
	var stamp string
	if t.IgnoreSecond {
		stamp = fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04"))
	} else {
		stamp = fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
	}

	return []byte(stamp), nil
}

// UnmarshalJSON 反序列化为JSON
func (t *Time20) UnmarshalJSON(data []byte) error {
	if string(data) == "\"\"" {
		return nil
	}
	var err error
	t.Time, err = time.Parse("2006-01-02 15:04:05", string(data)[1:20])
	return err
}

// String 重写String方法
func (t *Time20) String() string {
	data, _ := json.Marshal(t)
	return string(data)
}

// FieldType 数据类型
func (t *Time20) FieldType() int {
	return orm.TypeTimeField

}

// SetRaw 读取数据库值
func (t *Time20) SetRaw(value interface{}) error {
	switch value.(type) {
	case time.Time:
		t.Time = value.(time.Time)
	}
	return nil
}

// RawValue 写入数据库
func (t *Time20) RawValue() interface{} {
	str := t.Format("2006:01:02 15:04:05")
	if str == "0001:01:01 00:00:00" {
		return nil
	}
	return str
}

//写入数据库时会调用该方法将自定义时间类型转换并写入数据库
func (t Time20) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

//读取数据库时会调用该方法将时间数据转换成自定义时间类型
func (t *Time20) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = Time20{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

// MarshalJSON 序列化为JSON
func (t *Time10) MarshalJSON() ([]byte, error) {
	if t.IsZero() {
		return []byte("\"\""), nil
	}
	stamp := fmt.Sprintf("\"%s\"", t.Format("2006-01-02"))
	return []byte(stamp), nil
}

// UnmarshalJSON 反序列化为JSON
func (t *Time10) UnmarshalJSON(data []byte) error {
	var err error
	t.Time, err = time.Parse("2006-01-02", string(data)[1:11])
	return err
}

// String 重写String方法
func (t *Time10) String() string {
	data, _ := json.Marshal(t)
	return string(data)
}

// FieldType 数据类型
func (t *Time10) FieldType() int {
	return orm.TypeTimeField

}

// SetRaw 读取数据库值
func (t *Time10) SetRaw(value interface{}) error {
	switch value.(type) {
	case time.Time:
		t.Time = value.(time.Time)
	}
	return nil
}

// RawValue 写入数据库
func (t *Time10) RawValue() interface{} {
	str := t.Format("2006-01-02")
	if str == "0001-01-01" {
		return nil
	}
	return str
}
